﻿// Decompiled with JetBrains decompiler
// Type: TaleWorlds.CampaignSystem.Issues.LordWantsRivalCapturedIssueBehavior
// Assembly: TaleWorlds.CampaignSystem, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: E85F8C15-4DF6-4E9C-A58A-29177E40D07A
// Assembly location: D:\steam\steamapps\common\Mount & Blade II Bannerlord\bin\Win64_Shipping_Client\TaleWorlds.CampaignSystem.dll

using Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using TaleWorlds.CampaignSystem.Actions;
using TaleWorlds.CampaignSystem.CharacterDevelopment;
using TaleWorlds.CampaignSystem.Conversation;
using TaleWorlds.CampaignSystem.Encounters;
using TaleWorlds.CampaignSystem.GameMenus;
using TaleWorlds.CampaignSystem.MapEvents;
using TaleWorlds.CampaignSystem.Party;
using TaleWorlds.CampaignSystem.Roster;
using TaleWorlds.CampaignSystem.Settlements;
using TaleWorlds.Core;
using TaleWorlds.Localization;
using TaleWorlds.ObjectSystem;
using TaleWorlds.SaveSystem;

#nullable disable
namespace TaleWorlds.CampaignSystem.Issues
{
  public class LordWantsRivalCapturedIssueBehavior : CampaignBehaviorBase
  {
    private const IssueBase.IssueFrequency LordWantsRivalCapturedIssueFrequency = IssueBase.IssueFrequency.Rare;
    private const float TargetHeroRelationMaxRelation = -10f;

    public override void RegisterEvents()
    {
      CampaignEvents.OnCheckForIssueEvent.AddNonSerializedListener((object) this, new Action<Hero>(this.OnCheckForIssue));
    }

    public override void SyncData(IDataStore dataStore)
    {
    }

    private bool ConditionsHold(Hero issueGiver, out Hero targetHero)
    {
      targetHero = (Hero) null;
      if (issueGiver.IsLord && !issueGiver.IsMinorFactionHero && issueGiver.Clan.Leader == issueGiver && issueGiver.Clan != Clan.PlayerClan && issueGiver.GetTraitLevel(DefaultTraits.Mercy) <= 0 && issueGiver.GetTraitLevel(DefaultTraits.Honor) <= 0 && issueGiver.GetTraitLevel(DefaultTraits.Valor) <= 0)
      {
        List<Clan> list = Clan.FindAll((Predicate<Clan>) (x => x.MapFaction != issueGiver.MapFaction && x.MapFaction.IsAtWarWith(issueGiver.MapFaction) && x.Lords.Count > 0)).ToList<Clan>();
        int count = list.Count;
        if (count > 0)
        {
          int num = MBRandom.RandomInt(count);
          int index = num;
          bool flag = true;
          do
          {
            Clan clan = list[index];
            targetHero = clan.Lords.GetRandomElementWithPredicate<Hero>((Func<Hero, bool>) (noble => noble.IsAlive && !noble.IsKingdomLeader && noble.PartyBelongedTo != null && noble.PartyBelongedTo.MemberRoster.TotalHealthyCount >= 50 && (double) noble.GetRelation(issueGiver) <= -10.0));
            ++index;
            if (index == count)
              index = 0;
            if (index == num)
              flag = false;
          }
          while (targetHero == null & flag);
        }
      }
      return targetHero != null;
    }

    public void OnCheckForIssue(Hero hero)
    {
      Hero targetHero;
      if (this.ConditionsHold(hero, out targetHero))
        Campaign.Current.IssueManager.AddPotentialIssueData(hero, new PotentialIssueData(new PotentialIssueData.StartIssueDelegate(this.OnSelected), typeof (LordWantsRivalCapturedIssueBehavior.LordWantsRivalCapturedIssue), IssueBase.IssueFrequency.Rare, (object) targetHero));
      else
        Campaign.Current.IssueManager.AddPotentialIssueData(hero, new PotentialIssueData(typeof (LordWantsRivalCapturedIssueBehavior.LordWantsRivalCapturedIssue), IssueBase.IssueFrequency.Rare));
    }

    private IssueBase OnSelected(in PotentialIssueData pid, Hero issueOwner)
    {
      return (IssueBase) new LordWantsRivalCapturedIssueBehavior.LordWantsRivalCapturedIssue(issueOwner, pid.RelatedObject as Hero);
    }

    public class LordWantsRivalCapturedIssue : IssueBase
    {
      private const int QuestTimeLimit = 300;
      [SaveableField(10)]
      private Hero _targetHero;

      internal static void AutoGeneratedStaticCollectObjectsLordWantsRivalCapturedIssue(
        object o,
        List<object> collectedObjects)
      {
        ((MBObjectBase) o).AutoGeneratedInstanceCollectObjects(collectedObjects);
      }

      protected override void AutoGeneratedInstanceCollectObjects(List<object> collectedObjects)
      {
        base.AutoGeneratedInstanceCollectObjects(collectedObjects);
        collectedObjects.Add((object) this._targetHero);
      }

      internal static object AutoGeneratedGetMemberValue_targetHero(object o)
      {
        return (object) ((LordWantsRivalCapturedIssueBehavior.LordWantsRivalCapturedIssue) o)._targetHero;
      }

      protected override int RewardGold => 5000;

      public override TextObject IssueBriefByIssueGiver
      {
        get
        {
          TextObject parent = new TextObject("{=uc4M4bhG}Well, there is something I want. There is one {?TARGET_HERO.GENDER}lady{?}lord{\\?} of the {TARGET_FACTION} with whom I have a long, long relationship. And not a friendly one. Even though we are not now at war, as long as {?TARGET_HERO.GENDER}she{?}he{\\?} is free, I know my life and lands are not safe. As I say, it won't be easy at all. But whoever manages to do that, bring {?TARGET_HERO.GENDER}her{?}him{\\?} back alive to me, having my gratitude aside, will be a very rich man indeed.[if:convo_grave][ib:closed2]");
          StringHelpers.SetCharacterProperties("TARGET_HERO", this._targetHero.CharacterObject, parent);
          parent.SetTextVariable("TARGET_FACTION", this._targetHero.Clan.Name);
          return parent;
        }
      }

      public override TextObject IssueAcceptByPlayer
      {
        get
        {
          TextObject parent = new TextObject("{=tzBybYcf}I am interested. Who is this {?TARGET_HERO.GENDER}woman{?}man{\\?}?");
          StringHelpers.SetCharacterProperties("TARGET_HERO", this._targetHero.CharacterObject, parent);
          return parent;
        }
      }

      public override TextObject IssueQuestSolutionExplanationByIssueGiver
      {
        get
        {
          TextObject parent = new TextObject("{=zKhvUmeH}{?TARGET_HERO.GENDER}She{?}He{\\?} is {TARGET_HERO.NAME} from {TARGET_HERO.CLAN}. I want {?TARGET_HERO.GENDER}her{?}him{\\?} brought to me, so I can settle this score once and for all. I have {BASE_REWARD}{GOLD_ICON} that I have set aside. If you can bring me {TARGET_HERO.LINK} alive within a year, it is yours to claim.[if:convo_bared_teeth][ib:closed2]");
          StringHelpers.SetCharacterProperties("TARGET_HERO", this._targetHero.CharacterObject, parent, true);
          parent.SetTextVariable("BASE_REWARD", this.RewardGold);
          GameTexts.SetVariable("GOLD_ICON", "{=!}<img src=\"General\\Icons\\Coin@2x\" extend=\"8\">");
          return parent;
        }
      }

      public override TextObject IssueQuestSolutionAcceptByPlayer
      {
        get
        {
          TextObject parent = new TextObject("{=Ysjh2GF2}Hold on to that reward, then. I will bring {?TARGET_HERO.GENDER}her{?}him{\\?} alive.");
          StringHelpers.SetCharacterProperties("TARGET_HERO", this._targetHero.CharacterObject, parent);
          return parent;
        }
      }

      public override bool IsThereAlternativeSolution => false;

      public override bool IsThereLordSolution => false;

      public override TextObject Title
      {
        get
        {
          TextObject parent = new TextObject("{=FoNfLOny}{ISSUE_OWNER.NAME} wants {TARGET_HERO.NAME} captured");
          StringHelpers.SetCharacterProperties("ISSUE_OWNER", this.IssueOwner.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("TARGET_HERO", this._targetHero.CharacterObject, parent);
          return parent;
        }
      }

      public override TextObject Description
      {
        get
        {
          TextObject parent = new TextObject("{=FoNfLOny}{ISSUE_OWNER.NAME} wants {TARGET_HERO.NAME} captured");
          StringHelpers.SetCharacterProperties("ISSUE_OWNER", this.IssueOwner.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("TARGET_HERO", this._targetHero.CharacterObject, parent);
          return parent;
        }
      }

      public LordWantsRivalCapturedIssue(Hero issueOwner, Hero targetHero)
        : base(issueOwner, CampaignTime.DaysFromNow(20f))
      {
        this._targetHero = targetHero;
      }

      protected override float GetIssueEffectAmountInternal(IssueEffect issueEffect)
      {
        return issueEffect == DefaultIssueEffects.ClanInfluence ? -0.3f : 0.0f;
      }

      public override IssueBase.IssueFrequency GetFrequency() => IssueBase.IssueFrequency.Rare;

      public override bool IssueStayAliveConditions()
      {
        return !this._targetHero.IsDead && !this.IssueOwner.IsDead && !this._targetHero.IsPrisoner && this._targetHero.PartyBelongedTo != null && this.IssueOwner.MapFaction != this._targetHero.MapFaction && this.IssueOwner.Clan != Clan.PlayerClan;
      }

      protected override bool CanPlayerTakeQuestConditions(
        Hero issueGiver,
        out IssueBase.PreconditionFlags flags,
        out Hero relationHero,
        out SkillObject skill)
      {
        relationHero = (Hero) null;
        flags = IssueBase.PreconditionFlags.None;
        if ((double) issueGiver.GetRelationWithPlayer() < -10.0)
        {
          flags |= IssueBase.PreconditionFlags.Relation;
          relationHero = issueGiver;
        }
        if (issueGiver.MapFaction.IsAtWarWith(Hero.MainHero.MapFaction))
          flags |= IssueBase.PreconditionFlags.AtWar;
        if (Clan.PlayerClan.Tier < 2)
          flags |= IssueBase.PreconditionFlags.ClanTier;
        if (MobileParty.MainParty.MemberRoster.TotalHealthyCount < 50)
          flags |= IssueBase.PreconditionFlags.NotEnoughTroops;
        skill = (SkillObject) null;
        return flags == IssueBase.PreconditionFlags.None;
      }

      protected override void OnGameLoad()
      {
      }

      protected override void HourlyTick()
      {
      }

      protected override QuestBase GenerateIssueQuest(string questId)
      {
        return (QuestBase) new LordWantsRivalCapturedIssueBehavior.LordWantsRivalCapturedIssueQuest(questId, this.IssueOwner, CampaignTime.DaysFromNow(300f), this.RewardGold, this._targetHero);
      }

      protected override void CompleteIssueWithTimedOutConsequences()
      {
      }
    }

    public class LordWantsRivalCapturedIssueQuest : QuestBase
    {
      [SaveableField(1)]
      private Hero _targetHero;
      [SaveableField(2)]
      private bool _firstCounterOfferMade;
      private CharacterObject _questGiversAgentCharacterObject;

      internal static void AutoGeneratedStaticCollectObjectsLordWantsRivalCapturedIssueQuest(
        object o,
        List<object> collectedObjects)
      {
        ((MBObjectBase) o).AutoGeneratedInstanceCollectObjects(collectedObjects);
      }

      protected override void AutoGeneratedInstanceCollectObjects(List<object> collectedObjects)
      {
        base.AutoGeneratedInstanceCollectObjects(collectedObjects);
        collectedObjects.Add((object) this._targetHero);
      }

      internal static object AutoGeneratedGetMemberValue_targetHero(object o)
      {
        return (object) ((LordWantsRivalCapturedIssueBehavior.LordWantsRivalCapturedIssueQuest) o)._targetHero;
      }

      internal static object AutoGeneratedGetMemberValue_firstCounterOfferMade(object o)
      {
        return (object) ((LordWantsRivalCapturedIssueBehavior.LordWantsRivalCapturedIssueQuest) o)._firstCounterOfferMade;
      }

      private bool PlayerCapturedTargetHero
      {
        get
        {
          return MobileParty.MainParty.PrisonRoster.GetTroopRoster().Where<TroopRosterElement>((Func<TroopRosterElement, bool>) (x => x.Character.IsHero)).FirstOrDefault<TroopRosterElement>((Func<TroopRosterElement, bool>) (x => x.Character.HeroObject == this._targetHero)).Character != null;
        }
      }

      public override TextObject Title
      {
        get
        {
          TextObject parent = new TextObject("{=FoNfLOny}{ISSUE_OWNER.NAME} wants {TARGET_HERO.NAME} captured");
          StringHelpers.SetCharacterProperties("ISSUE_OWNER", this.QuestGiver.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("TARGET_HERO", this._targetHero.CharacterObject, parent);
          return parent;
        }
      }

      public override bool IsRemainingTimeHidden => false;

      private TextObject _playerStartsQuestLogText
      {
        get
        {
          TextObject parent = new TextObject("{=nB07bljx}{ISSUE_OWNER.LINK}, a {?ISSUE_OWNER.GENDER}lady{?}lord{\\?} of the {ISSUE_OWNER.CLAN}, has a personal vendetta against {TARGET_HERO.LINK} of the {TARGET_HERO.CLAN}. {?ISSUE_OWNER.GENDER}She{?}He{\\?} wants {TARGET_HERO.LINK} captured and brought back to {?ISSUE_OWNER.GENDER}her{?}him{\\?}. If you manage doing that, {?ISSUE_OWNER.GENDER}she{?}he{\\?} promised a reward of {REWARD_GOLD}{GOLD_ICON}. You agreed to find {TARGET_HERO.LINK} and bring {?TARGET_HERO.GENDER}her{?}him{\\?} to {ISSUE_OWNER.LINK} within one year.");
          StringHelpers.SetCharacterProperties("ISSUE_OWNER", this.QuestGiver.CharacterObject, parent, true);
          StringHelpers.SetCharacterProperties("TARGET_HERO", this._targetHero.CharacterObject, parent, true);
          parent.SetTextVariable("REWARD_GOLD", this.RewardGold);
          return parent;
        }
      }

      private TextObject _playerAcceptedOfferQuestFail
      {
        get
        {
          TextObject parent = new TextObject("{=vh4bBfYq}You have accepted {TARGET_HERO.LINK}'s offer and freed {?TARGET_HERO.GENDER}her{?}him{\\?}. {?TARGET_HERO.GENDER}She{?}He{\\?} and {?TARGET_HERO.GENDER}her{?}his{\\?} clan would be very happy. On the other hand {ISSUE_OWNER.LINK} will feel {?ISSUE_OWNER.GENDER}she{?}he{\\?} is betrayed and be furious.");
          StringHelpers.SetCharacterProperties("ISSUE_OWNER", this.QuestGiver.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("TARGET_HERO", this._targetHero.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject _playerDeliveredPrisonerQuestSuccess
      {
        get
        {
          TextObject parent = new TextObject("{=UIyhmGKC}You have handed over the prisoner {TARGET_HERO.LINK} to {ISSUE_OWNER.LINK}'s agent, who handed you {BASE_REWARD}{GOLD_ICON} denars as promised. He also says; {ISSUE_OWNER.LINK} is grateful for your service and sends {?ISSUE_OWNER.GENDER}her{?}his{\\?} regards.");
          StringHelpers.SetCharacterProperties("ISSUE_OWNER", this.QuestGiver.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("TARGET_HERO", this._targetHero.CharacterObject, parent);
          parent.SetTextVariable("BASE_REWARD", this.RewardGold);
          GameTexts.SetVariable("GOLD_ICON", "{=!}<img src=\"General\\Icons\\Coin@2x\" extend=\"8\">");
          return parent;
        }
      }

      private TextObject _playerCapturedTargetBrief1LogText
      {
        get
        {
          TextObject parent = new TextObject("{=VdGyUQH0}You have captured {TARGET_HERO.LINK}. It looks like {?TARGET_HERO.GENDER}she{?}he{\\?} is desperate and very afraid of being sent to {ISSUE_OWNER.LINK} so for {?TARGET_HERO.GENDER}her{?}his{\\?} release, {?TARGET_HERO.GENDER}she{?}he{\\?} offers a sum of {BASE_REWARD_X_2}{GOLD_ICON} denars, double of what {ISSUE_OWNER.LINK} was willing to pay for his capture. {ISSUE_OWNER.LINK} on the other hand sends you a letter soon after {TARGET_HERO.LINK}'s capture. The letter reads:");
          StringHelpers.SetCharacterProperties("ISSUE_OWNER", this.QuestGiver.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("TARGET_HERO", this._targetHero.CharacterObject, parent);
          parent.SetTextVariable("BASE_REWARD_X_2", this.RewardGold * 2);
          GameTexts.SetVariable("GOLD_ICON", "{=!}<img src=\"General\\Icons\\Coin@2x\" extend=\"8\">");
          return parent;
        }
      }

      private TextObject _playerCapturedTargetBrief2LogText
      {
        get
        {
          TextObject parent = new TextObject("{=vzF9atyv}My dear {PLAYER.NAME}, I have been informed that you have captured {TARGET_HERO.LINK}. This is great news. One of my agents will wait for you at the gates of the next settlement that belongs to my clan with the bounty I promised. You should deliver your prisoner to him as soon as you can. I have plans for {?TARGET_HERO.GENDER}her{?}him{\\?}. Thank you and best wishes, - {ISSUE_OWNER.LINK}");
          StringHelpers.SetCharacterProperties("ISSUE_OWNER", this.QuestGiver.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("PLAYER", CharacterObject.PlayerCharacter, parent);
          StringHelpers.SetCharacterProperties("TARGET_HERO", this._targetHero.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject _playerCapturedTargetBrief3LogText
      {
        get
        {
          TextObject parent = new TextObject("{=1H6SKtUl}Deliver the prisoner to {ISSUE_OWNER.LINK} {?ISSUE_OWNER.GENDER}herself{?}himself{\\?} or one of {?ISSUE_OWNER.GENDER}her{?}his{\\?} settlements. If you don't want to deliver {TARGET_HERO.LINK}, talk with {?TARGET_HERO.GENDER}her{?}him{\\?} to negotiate on {?TARGET_HERO.GENDER}her{?}his{\\?} release.");
          StringHelpers.SetCharacterProperties("TARGET_HERO", this._targetHero.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("ISSUE_OWNER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject _targetKilledByPlayerLogText
      {
        get
        {
          TextObject parent = new TextObject("{=GlfwOWre}You have received a letter from {ISSUE_OWNER.LINK}; It reads: \"My dear {PLAYER.NAME}, I have been informed that that vile creature called {TARGET_HERO.LINK} has been slain by you! While this is great news, I had other plans for {?TARGET_HERO.GENDER}her{?}him{\\?}. What a pity. Anyway, I am feeling generous. So I will still pay half of what we had previously agreed upon. The messenger who brought you this note should give you the sum. Best wishes - {ISSUE_OWNER.LINK}\"");
          StringHelpers.SetCharacterProperties("TARGET_HERO", this._targetHero.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("PLAYER", CharacterObject.PlayerCharacter, parent);
          StringHelpers.SetCharacterProperties("ISSUE_OWNER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject _questGiverCapturedTargetHero
      {
        get
        {
          TextObject parent = new TextObject("{=2HIE7n9G}{ISSUE_OWNER.LINK} has captured {TARGET_HERO.LINK} {?ISSUE_OWNER.GENDER}herself{?}himself{\\?}, your contract with {ISSUE_OWNER.LINK} has canceled.");
          StringHelpers.SetCharacterProperties("TARGET_HERO", this._targetHero.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("ISSUE_OWNER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject _targetHeroAndQuestGiverInSameFaction
      {
        get
        {
          TextObject parent = new TextObject("{=4JE6bYIE}{ISSUE_OWNER.LINK} and {TARGET_HERO.LINK} are now part of the same faction so they can't fight against each other. Your contract with {ISSUE_OWNER.LINK} has canceled.");
          StringHelpers.SetCharacterProperties("ISSUE_OWNER", this.QuestGiver.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("TARGET_HERO", this._targetHero.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject _warDeclaredQuestLog
      {
        get
        {
          TextObject declaredQuestLog = new TextObject("{=cKz1cyuM}Your clan is now at war with {QUEST_GIVER_SETTLEMENT_FACTION}. Quest is canceled.");
          declaredQuestLog.SetTextVariable("QUEST_GIVER_SETTLEMENT_FACTION", this.QuestGiver.MapFaction.Name);
          return declaredQuestLog;
        }
      }

      private TextObject _timeOutLogText
      {
        get => new TextObject("{=maXW8tps}You failed to capture and deliver the prisoner in time.");
      }

      public LordWantsRivalCapturedIssueQuest(
        string questId,
        Hero giverHero,
        CampaignTime duration,
        int rewardGold,
        Hero targetHero)
        : base(questId, giverHero, duration, rewardGold)
      {
        this._targetHero = targetHero;
        this.SetDialogs();
        this.InitializeQuestOnCreation();
        this._firstCounterOfferMade = false;
        this._questGiversAgentCharacterObject = (CharacterObject) null;
      }

      private bool DialogCondition()
      {
        StringHelpers.SetCharacterProperties("TARGET_HERO", this._targetHero.CharacterObject);
        StringHelpers.SetCharacterProperties("PLAYER", CharacterObject.PlayerCharacter);
        return Hero.OneToOneConversationHero == this.QuestGiver;
      }

      protected override void SetDialogs()
      {
        this.OfferDialogFlow = DialogFlow.CreateDialogFlow("issue_classic_quest_start").NpcLine(new TextObject("{=qaKh6vRl}Let's see if you are as good as your word. If you really manage, I admit, I will be very impressed. I look forward to meeting you again.[if:convo_mocking_aristocratic][ib:closed]")).Condition(new ConversationSentence.OnConditionDelegate(this.DialogCondition)).Consequence(new ConversationSentence.OnConsequenceDelegate(this.QuestAcceptedConsequences)).CloseDialog();
        this.DiscussDialogFlow = DialogFlow.CreateDialogFlow("quest_discuss").NpcLine(new TextObject("{=xFHb9nAk}Have you been able to find {?TARGET_HERO.GENDER}her{?}his{\\?} whereabouts yet?")).Condition(new ConversationSentence.OnConditionDelegate(this.DialogCondition)).Consequence((ConversationSentence.OnConsequenceDelegate) (() => Campaign.Current.ConversationManager.ConversationEndOneShot += new Action(MapEventHelper.OnConversationEnd))).BeginPlayerOptions().PlayerOption(new TextObject("{=ZkVP4RYV}Yes, I've captured {?TARGET_HERO.GENDER}her{?}him{\\?}.")).Condition((ConversationSentence.OnConditionDelegate) (() => this.PlayerCapturedTargetHero)).NpcLine(new TextObject("{=qvlln5ej}Thanks, I knew I could trust you.[if:convo_happy][ib:confident2]")).Consequence((ConversationSentence.OnConsequenceDelegate) (() => Campaign.Current.ConversationManager.ConversationEndOneShot += new Action(this.PlayerDeliveredPrisonerQuestSuccess))).CloseDialog().PlayerOption(new TextObject("{=fwQtClVo}I will deal with {?TARGET_HERO.GENDER}her{?}him{\\?} right away! ")).NpcLine(new TextObject("{=fr4F4IQc}It's good to hear that, {PLAYER.NAME}.[if:convo_relaxed_happy][ib:hip] ")).CloseDialog().PlayerOption(new TextObject("{=18NtjryL}Not yet, but I will soon.")).NpcLine(new TextObject("{=zs8rZnf8}I will be waiting for your good news {PLAYER.NAME}.[if:convo_relaxed_happy][ib:hip]")).CloseDialog().EndPlayerOptions();
        Campaign.Current.ConversationManager.AddDialogFlow(this.GetTargetHeroDialogFlow(), (object) this);
        Campaign.Current.ConversationManager.AddDialogFlow(this.GetTargetHeroCounterOffer1DialogFlow(), (object) this);
        Campaign.Current.ConversationManager.AddDialogFlow(this.GetTargetHeroCounterOffer2DialogFlow(), (object) this);
        Campaign.Current.ConversationManager.AddDialogFlow(this.GetQuestGiversAgentDialogFlow(), (object) this);
      }

      private DialogFlow GetTargetHeroDialogFlow()
      {
        TextObject textObject1 = new TextObject("{=Mn4bI9Jg}What are you doing? Are you another one of {QUEST_GIVER.NAME}'s lackeys? Do you think you can hunt me like an animal.[if:convo_confused_normal][ib:closed]");
        StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, textObject1);
        TextObject textObject2 = new TextObject("{=qOhDHFyH}Are you another one of {QUEST_GIVER.NAME}'s lackeys? Did {?QUEST_GIVER.GENDER}she{?}he{\\?} send you to hunt me like an animal? Well, I think you've found you've caught not a hare but a lion.[if:convo_confused_annoyed][ib:aggressive]");
        StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, textObject2);
        return DialogFlow.CreateDialogFlow("start", 125).BeginNpcOptions().NpcOption(textObject2, new ConversationSentence.OnConditionDelegate(this.target_hero_encounter_agressive_condition)).NpcLine(new TextObject("{=TzvGs0v1}Well I guess it's too late to change your mind now, I decided to make an example of you.[if:convo_furious][ib:warrior]")).CloseDialog().NpcOption(textObject1, new ConversationSentence.OnConditionDelegate(this.target_hero_encounter_default_condition)).BeginPlayerOptions().PlayerOption(new TextObject("{=WoAgHDrN}I'm bringing you in, one way or the other.")).NpcLine(new TextObject("{=hzCTbbLP}You think you've caught a hare but instead you've caught a lion.[if:convo_furious][ib:warrior]")).Consequence(new ConversationSentence.OnConsequenceDelegate(this.player_target_hero_encounter_consequence)).CloseDialog().PlayerOption(new TextObject("{=pZm7HRDG}Don't worry I have no intention to attack.")).NpcLine(new TextObject("{=eJuvk4om}Wise decision.[ib:closed][if:convo_bared_teeth]")).Consequence((ConversationSentence.OnConsequenceDelegate) (() => PlayerEncounter.LeaveEncounter = true)).CloseDialog().EndPlayerOptions().EndNpcOptions();
      }

      private DialogFlow GetTargetHeroCounterOffer1DialogFlow()
      {
        TextObject textObject = new TextObject("{=dYa9oVSP}Fate is cruel. So, I am your prisoner. But you don't need to do {QUEST_GIVER.NAME}'s dirty work. For the sake of your honor, {?PLAYER.GENDER}lady{?}sir{\\?}, listen to me![if:convo_nervous2][ib:nervous]");
        StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, textObject);
        StringHelpers.SetCharacterProperties("PLAYER", CharacterObject.PlayerCharacter, textObject);
        TextObject npcText1 = new TextObject("{=zliqo1Y8}{?PLAYER.GENDER}Madam{?}Sir{\\?}, I will pay double whatever {?QUEST_GIVER.GENDER}she{?}he{\\?} promised to release me. Believe me, you don't want a reputation as {?QUEST_GIVER.GENDER}her{?}his{\\?} kidnapper-for-hire.[if:convo_grave][ib:normal2]");
        StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, textObject);
        StringHelpers.SetCharacterProperties("PLAYER", CharacterObject.PlayerCharacter, textObject);
        TextObject npcText2 = new TextObject("{=uBcBuDKV}It's no worse than taking {QUEST_GIVER.NAME}'s silver in the first place for this task. Do think it over.[if:convo_normal][ib:normal]");
        StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, textObject);
        return DialogFlow.CreateDialogFlow("start", 125).NpcLine(textObject).Condition(new ConversationSentence.OnConditionDelegate(this.after_taken_prisoner_counter_offer_condition)).Consequence(new ConversationSentence.OnConsequenceDelegate(this.FirstCounterOfferFinished)).BeginPlayerOptions().PlayerOption(new TextObject("{=SJfqzt8m}Go on... I'm listening")).NpcLine(npcText1).BeginPlayerOptions().PlayerOption(new TextObject("{=rFriAZcL}Can you really pay me {BASE_REWARD_X_2}{GOLD_ICON} for your freedom?")).Condition(new ConversationSentence.OnConditionDelegate(this.set_reward_x_2_and_gold_icon)).NpcLine(new TextObject("{=59ijHPtR}Yes. That is a lot but yes I can pay that.[if:convo_nonchalant][ib:confident]")).BeginPlayerOptions().PlayerOption(new TextObject("{=E8wdxbui}All right, I accept. I release you now. Now pay me.")).NpcLine(new TextObject("{=bWbcuOji}Yes. That is a lot but yes I can pay that. Thank you {?PLAYER.GENDER}milady{?}my Lord{\\?}. I knew we could reach an agreement.[if:convo_grateful][ib:confident]")).Consequence(new ConversationSentence.OnConsequenceDelegate(this.QuestFailCounterOfferAccepted)).CloseDialog().PlayerOption(new TextObject("{=MacG8ikN}I will think about it.")).NpcLine(new TextObject("{=UKTjwBxk}Please be quick about it!")).CloseDialog().EndPlayerOptions().PlayerOption(new TextObject("{=czuvE3PC}Do you think I will break my word for a handful more silver?")).NpcLine(npcText2).CloseDialog().EndPlayerOptions().PlayerOption(new TextObject("{=2v0eQ755}Sorry, not interested.")).NpcLine(new TextObject("{=D1biQObM}I will pay double whatever {ISSUE_OWNER.NAME} is paying you! Please consider my offer![if:convo_nervous2][ib:nervous]")).CloseDialog().EndPlayerOptions();
      }

      private DialogFlow GetTargetHeroCounterOffer2DialogFlow()
      {
        return DialogFlow.CreateDialogFlow("start", 125).NpcLine(new TextObject("{=QDMbaUYv}My {?PLAYER.GENDER}lady{?}lord{\\?}! please tell me you have decided to release me.[if:convo_nervous]")).Condition(new ConversationSentence.OnConditionDelegate(this.counter_offer_2_condition)).BeginPlayerOptions().PlayerOption(new TextObject("{=tNo1Dctm}Yes. If you pay me {BASE_REWARD_X_2}{GOLD_ICON}, I will release you")).Condition(new ConversationSentence.OnConditionDelegate(this.set_reward_x_2_and_gold_icon)).NpcLine(new TextObject("{=jeljPTgV}Thank you, my {?PLAYER.GENDER}lady{?}lord{\\?}. I knew we could reach an agreement.")).Consequence(new ConversationSentence.OnConsequenceDelegate(this.QuestFailCounterOfferAccepted)).PlayerOption(new TextObject("{=AOgrLJos}No. I haven't decided yet.")).NpcLine(new TextObject("{=UKTjwBxk}Please be quick about it!")).CloseDialog().EndPlayerOptions();
      }

      private DialogFlow GetQuestGiversAgentDialogFlow()
      {
        return DialogFlow.CreateDialogFlow("start", 125).NpcLine(new TextObject("{=lYhWyuCM}Greetings {?PLAYER.GENDER}milady{?}sir{\\?}, {QUEST_GIVER.NAME} has sent me to collect {TARGET_HERO.NAME}.[if:convo_nonchalant][ib:demure2]")).Condition(new ConversationSentence.OnConditionDelegate(this.quest_givers_agent_dialog_condition)).NpcLine(new TextObject("{=1PCaW5YI}My liege {QUEST_GIVER.NAME} also instructed me to present you the sum of {REWARD_GOLD}{GOLD_ICON} denars for the prisoners exchange.")).NpcLine(new TextObject("{=Mt1cSesD}My {?PLAYER.GENDER}lady{?}lord{\\?} also instructed me to express {?PLAYER.GENDER}her{?}his{\\?} gratitude for your services, and admiration for your skill.[if:convo_bemused][ib:demure]")).BeginPlayerOptions().PlayerOption(new TextObject("{=itHCs6bB}I'm delivering {?TARGET_HERO.GENDER}her{?}him{\\?} as I promised.")).NpcLine(new TextObject("{=RScf2bnd}Thank you {?PLAYER.GENDER}milady{?}sir{\\?}. My liege {?QUEST_GIVER.GENDER}lady{?}lord{\\?} {QUEST_GIVER.NAME} sends {?QUEST_GIVER.GENDER}her{?}his{\\?} regards. Here is the reward {?QUEST_GIVER.GENDER}she{?}he{\\?} has promised. I must take my leave now.[if:convo_bemused][ib:demure]")).Consequence(new ConversationSentence.OnConsequenceDelegate(this.PlayerDeliveredPrisonerQuestSuccess)).CloseDialog().PlayerOption(new TextObject("{=uHY7NqZf}I can't do this. I am releasing {TARGET_HERO.NAME}. Tell your master that {TARGET_HERO.NAME} is no longer a prisoner.")).NpcLine(new TextObject("{=A8NttdZY}My {?QUEST_GIVER.GENDER}lady{?}lord{\\?} will be furious that you are going back on your word.[if:convo_annoyed][ib:closed2]")).PlayerLine(new TextObject("{=UaSddsa2}My decision is final.")).NpcLine(new TextObject("{=XrUPGyRO}You will regret your decision...[if:convo_grave][ib:closed]")).CloseDialog().EndPlayerOptions().Consequence(new ConversationSentence.OnConsequenceDelegate(this.QuestFailCounterOfferAccepted));
      }

      private bool quest_givers_agent_dialog_condition()
      {
        StringHelpers.SetCharacterProperties("TARGET_HERO", this._targetHero.CharacterObject);
        StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject);
        StringHelpers.SetCharacterProperties("PLAYER", CharacterObject.PlayerCharacter);
        MBTextManager.SetTextVariable("REWARD_GOLD", this.RewardGold);
        GameTexts.SetVariable("GOLD_ICON", "{=!}<img src=\"General\\Icons\\Coin@2x\" extend=\"8\">");
        return CharacterObject.OneToOneConversationCharacter == this._questGiversAgentCharacterObject;
      }

      private void FirstCounterOfferFinished()
      {
        this._firstCounterOfferMade = true;
        TakePrisonerAction.Apply(PartyBase.MainParty, this._targetHero);
      }

      private bool common_first_dialogue_condition()
      {
        return Hero.OneToOneConversationHero == this._targetHero && this._targetHero.CurrentSettlement == null && !this.PlayerCapturedTargetHero && Campaign.Current.CurrentConversationContext != ConversationContext.CapturedLord;
      }

      private void player_target_hero_encounter_consequence() => GameMenu.SwitchToMenu("encounter");

      private bool target_hero_encounter_agressive_condition()
      {
        return this.common_first_dialogue_condition() && this._targetHero.MapFaction.IsAtWarWith(Hero.MainHero.MapFaction);
      }

      private bool target_hero_encounter_default_condition()
      {
        return this.common_first_dialogue_condition() && !FactionManager.IsAlliedWithFaction(this._targetHero.MapFaction, Hero.MainHero.MapFaction);
      }

      private bool after_taken_prisoner_counter_offer_condition()
      {
        if (Campaign.Current.CurrentConversationContext != ConversationContext.CapturedLord)
          return false;
        StringHelpers.SetCharacterProperties("ISSUE_OWNER", this.QuestGiver.CharacterObject);
        StringHelpers.SetCharacterProperties("PLAYER", CharacterObject.PlayerCharacter);
        return Hero.OneToOneConversationHero == this._targetHero && !this._firstCounterOfferMade;
      }

      private bool counter_offer_2_condition()
      {
        StringHelpers.SetCharacterProperties("PLAYER", CharacterObject.PlayerCharacter);
        return Hero.OneToOneConversationHero == this._targetHero && this.PlayerCapturedTargetHero && this._firstCounterOfferMade;
      }

      private bool set_reward_x_2_and_gold_icon()
      {
        MBTextManager.SetTextVariable("BASE_REWARD_X_2", this.RewardGold * 2);
        GameTexts.SetVariable("GOLD_ICON", "{=!}<img src=\"General\\Icons\\Coin@2x\" extend=\"8\">");
        return true;
      }

      private void QuestFailCounterOfferAccepted()
      {
        GiveGoldAction.ApplyBetweenCharacters((Hero) null, Hero.MainHero, this.RewardGold * 2);
        ChangeRelationAction.ApplyPlayerRelation(this._targetHero, 10);
        this.RelationshipChangeWithQuestGiver = -15;
        EndCaptivityAction.ApplyByReleasedByChoice(new FlattenedTroopRoster(1)
        {
          {
            this._targetHero.CharacterObject,
            false,
            0
          }
        });
        this.AddLog(this._playerAcceptedOfferQuestFail);
        this.CompleteQuestWithBetrayal();
      }

      private void PlayerDeliveredPrisonerQuestSuccess()
      {
        GiveGoldAction.ApplyBetweenCharacters((Hero) null, Hero.MainHero, this.RewardGold);
        ChangeRelationAction.ApplyPlayerRelation(this._targetHero, -10);
        this.RelationshipChangeWithQuestGiver = 15;
        this.AddLog(this._playerDeliveredPrisonerQuestSuccess);
        this.CompleteQuestWithSuccess();
        if (Hero.OneToOneConversationHero == this.QuestGiver)
          TransferPrisonerAction.Apply(this._targetHero.CharacterObject, PartyBase.MainParty, this.QuestGiver.PartyBelongedTo != null ? this.QuestGiver.PartyBelongedTo.Party : this.QuestGiver.CurrentSettlement.Party);
        else
          TransferPrisonerAction.Apply(this._targetHero.CharacterObject, PartyBase.MainParty, Settlement.CurrentSettlement.Party);
      }

      private void QuestAcceptedConsequences()
      {
        this.StartQuest();
        this.AddLog(this._playerStartsQuestLogText);
      }

      protected override void OnTimedOut()
      {
        this.RelationshipChangeWithQuestGiver = -5;
        this.AddLog(this._timeOutLogText);
      }

      protected override void InitializeQuestOnGameLoad() => this.SetDialogs();

      protected override void HourlyTick()
      {
      }

      protected override void RegisterEvents()
      {
        CampaignEvents.OnPlayerBattleEndEvent.AddNonSerializedListener((object) this, new Action<MapEvent>(this.OnPlayerBattleEventEnded));
        CampaignEvents.HeroPrisonerTaken.AddNonSerializedListener((object) this, new Action<PartyBase, Hero>(this.OnPrisonerTaken));
        CampaignEvents.WarDeclared.AddNonSerializedListener((object) this, new Action<IFaction, IFaction, DeclareWarAction.DeclareWarDetail>(this.OnWarDeclared));
        CampaignEvents.OnClanChangedKingdomEvent.AddNonSerializedListener((object) this, new Action<Clan, Kingdom, Kingdom, ChangeKingdomAction.ChangeKingdomActionDetail, bool>(this.OnClanChangedKingdom));
        CampaignEvents.HeroPrisonerReleased.AddNonSerializedListener((object) this, new Action<Hero, PartyBase, IFaction, EndCaptivityDetail>(this.OnHeroPrisonerReleased));
        CampaignEvents.SettlementEntered.AddNonSerializedListener((object) this, new Action<MobileParty, Settlement, Hero>(this.OnSettlementEntered));
        CampaignEvents.HeroKilledEvent.AddNonSerializedListener((object) this, new Action<Hero, Hero, KillCharacterAction.KillCharacterActionDetail, bool>(this.OnHeroKilled));
        CampaignEvents.MapEventStarted.AddNonSerializedListener((object) this, new Action<MapEvent, PartyBase, PartyBase>(this.OnMapEventStarted));
      }

      private void OnMapEventStarted(
        MapEvent mapEvent,
        PartyBase attackerParty,
        PartyBase defenderParty)
      {
        if (!QuestHelper.CheckMinorMajorCoercion((QuestBase) this, mapEvent, attackerParty))
          return;
        QuestHelper.ApplyGenericMinorMajorCoercionConsequences((QuestBase) this, mapEvent);
      }

      private void OnHeroPrisonerReleased(
        Hero prisoner,
        PartyBase party,
        IFaction capturerFaction,
        EndCaptivityDetail detail)
      {
        if (!this.IsOngoing || !this.PlayerCapturedTargetHero || prisoner != this._targetHero)
          return;
        TextObject textObject = new TextObject("{=VuwaQjUN}{TARGET_HERO.LINK} has managed to escape and {?TARGET_HERO.GENDER}she{?}he{\\?} is no longer a prisoner.");
        StringHelpers.SetCharacterProperties("TARGET_HERO", this._targetHero.CharacterObject, textObject);
        this.AddLog(textObject);
        this._firstCounterOfferMade = false;
      }

      private void OnWarDeclared(
        IFaction faction1,
        IFaction faction2,
        DeclareWarAction.DeclareWarDetail detail)
      {
        this.CheckCancelConditions(DiplomacyHelper.IsWarCausedByPlayer(faction1, faction2, detail));
      }

      private void OnClanChangedKingdom(
        Clan clan,
        Kingdom oldKingdom,
        Kingdom newKingdom,
        ChangeKingdomAction.ChangeKingdomActionDetail detail,
        bool showNotification = true)
      {
        this.CheckCancelConditions();
      }

      private void OnHeroKilled(
        Hero victim,
        Hero killer,
        KillCharacterAction.KillCharacterActionDetail detail,
        bool showNotification = true)
      {
        if (victim != this._targetHero || killer != Hero.MainHero)
          return;
        this.AddLog(this._targetKilledByPlayerLogText);
        GainRenownAction.Apply(Hero.MainHero, 10f);
        this.RelationshipChangeWithQuestGiver = 10;
        this.CompleteQuestWithSuccess();
      }

      private void OnSettlementEntered(MobileParty party, Settlement settlement, Hero hero)
      {
        if (!this.PlayerCapturedTargetHero || hero != Hero.MainHero || party != MobileParty.MainParty || !settlement.IsFortification || settlement.OwnerClan != this.QuestGiver.Clan)
          return;
        this._questGiversAgentCharacterObject = this.QuestGiver.Culture.Guard;
        CampaignMapConversation.OpenConversation(new ConversationCharacterData(CharacterObject.PlayerCharacter, PartyBase.MainParty), new ConversationCharacterData(this._questGiversAgentCharacterObject));
      }

      private void OnPlayerBattleEventEnded(MapEvent mapEvent)
      {
        if (!mapEvent.IsPlayerMapEvent && !mapEvent.IsPlayerSimulation || !mapEvent.PartiesOnSide(mapEvent.GetOtherSide(mapEvent.PlayerSide)).Any<MapEventParty>((Func<MapEventParty, bool>) (x => x.Party.Owner == this._targetHero)) || !mapEvent.HasWinner || mapEvent.WinningSide != mapEvent.PlayerSide || this._targetHero.MapFaction.IsAtWarWith(Hero.MainHero.MapFaction))
          return;
        ChangeRelationAction.ApplyPlayerRelation(this._targetHero.MapFaction.Leader, -10);
        DeclareWarAction.ApplyByPlayerHostility(Hero.MainHero.MapFaction, this._targetHero.MapFaction);
      }

      private void OnPrisonerTaken(PartyBase capturer, Hero prisoner)
      {
        if (prisoner != this._targetHero)
          return;
        if (capturer == PartyBase.MainParty)
        {
          this.AddLog(this._playerCapturedTargetBrief1LogText);
          this.AddLog(this._playerCapturedTargetBrief2LogText);
          this.AddLog(this._playerCapturedTargetBrief3LogText);
        }
        else if (this.QuestGiver.PartyBelongedTo != null && capturer == this.QuestGiver.PartyBelongedTo.Party)
        {
          if (!this.IsOngoing)
            return;
          this.AddLog(this._questGiverCapturedTargetHero);
          this.CompleteQuestWithCancel();
        }
        else
        {
          TextObject textObject = TextObject.Empty;
          if (capturer.IsMobile)
          {
            textObject = new TextObject("{=gq8sgb2J}{TARGET_HERO.LINK} has been taken prisoner by {OTHER_HERO.LINK}.");
            StringHelpers.SetCharacterProperties("TARGET_HERO", this._targetHero.CharacterObject, textObject);
            StringHelpers.SetCharacterProperties("OTHER_HERO", ConversationHelper.GetConversationCharacterPartyLeader(capturer), textObject);
          }
          else if (capturer.IsSettlement)
          {
            textObject = new TextObject("{=HkvlHhPN}{TARGET_HERO.LINK} has been taken prisoner and thrown into the dungeons of {SETTLEMENT}.");
            StringHelpers.SetCharacterProperties("TARGET_HERO", this._targetHero.CharacterObject, textObject);
            textObject.SetTextVariable("SETTLEMENT", capturer.Settlement.EncyclopediaLinkWithName);
          }
          if (textObject == TextObject.Empty)
            return;
          this.AddLog(textObject);
        }
      }

      private void CheckCancelConditions(bool causedByPlayer = false)
      {
        if (!this.IsOngoing)
          return;
        if (this.QuestGiver.MapFaction.IsAtWarWith(Hero.MainHero.MapFaction))
        {
          if (causedByPlayer)
            this.CompleteQuestWithFail();
          else
            this.CompleteQuestWithCancel();
          this.AddLog(this._warDeclaredQuestLog);
        }
        else
        {
          if (this.QuestGiver.MapFaction != this._targetHero.MapFaction)
            return;
          this.CompleteQuestWithCancel();
          this.AddLog(this._targetHeroAndQuestGiverInSameFaction);
        }
      }
    }

    public class LordWantsRivalCapturedIssueTypeDefiner : SaveableTypeDefiner
    {
      public LordWantsRivalCapturedIssueTypeDefiner()
        : base(51400)
      {
      }

      protected override void DefineClassTypes()
      {
        this.AddClassDefinition(typeof (LordWantsRivalCapturedIssueBehavior.LordWantsRivalCapturedIssue), 1);
        this.AddClassDefinition(typeof (LordWantsRivalCapturedIssueBehavior.LordWantsRivalCapturedIssueQuest), 2);
      }
    }
  }
}
